package com.photo.util;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Images.ImageColumns;

import com.bumptech.glide.Glide;
import com.photo.LogUtil;
import com.photo.application.XbbApplication;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;

/**
 * @author zhangxiaowei
 * @version 1.0
 * @date 2014-9-2
 */
@SuppressLint("NewApi")
public class ImageUtil {
    private final String TAG = LogUtil.DEGUG_MODE ? "GlobalAlarmUtil"
            : ImageUtil.class.getSimpleName();
    private final boolean debug = true;
    private final int IO_BUFFER_SIZE = 2 * 1024;
    static ImageUtil imageUtil;

    public static ImageUtil getInstance() {
        if (imageUtil == null) {
            imageUtil = new ImageUtil();
        }
        return imageUtil;
    }

    public String getCameraPath() {
        return Environment
                .getExternalStorageDirectory() + "/images/";
    }

    /**
     * 根据指定的图像路径和大小来获取缩略图 此方法有两点好处： 1.
     * 使用较小的内存空间，第一次获取的bitmap实际上为null，只是为了读取宽度和高度，
     * 第二次读取的bitmap是根据比例压缩过的图像，第三次读取的bitmap是所要的缩略图。 2.
     * 缩略图对于原图像来讲没有拉伸，这里使用了2.2版本的新工具ThumbnailUtils，使 用这个工具生成的图像不会被拉伸。
     *
     * @param imagePath 图像的路径
     *                  //     * @param width     指定输出图像的宽度
     *                  //     * @param height    指定输出图像的高度
     * @return 生成的缩略图
     */
    public Bitmap getImageThumbnail(String imagePath) {
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // 获取这个图片的宽和高，注意此处的bitmap为null
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        options.inJustDecodeBounds = false; // 设为 false
        // 计算缩放比
        int h = options.outHeight;
        int w = options.outWidth;
        int width = 120;
        int height = 120;
        int beWidth = w / width;
        int beHeight = h / height;
        int be = 1;
        if (beWidth < beHeight) {
            be = beWidth;
        } else {
            be = beHeight;
        }
        if (be <= 0) {
            be = 1;
        }
        options.inSampleSize = be;
        // 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        // 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return (bitmap);
    }

    // 生成圆角图片
    public Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
        try {
            Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                    bitmap.getHeight(), Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight());
            final RectF rectF = new RectF(new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight()));
            final float roundPx = 8;
            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(Color.BLACK);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
            paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
            final Rect src = new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight());
            canvas.drawBitmap(bitmap, src, rect, paint);
            return output;
        } catch (Exception e) {
            return bitmap;
        }
    }

    /**
     * 获取视频的缩略图 先通过ThumbnailUtils来创建一个视频的缩略图，然后再利用ThumbnailUtils来生成指定大小的缩略图。
     * 如果想要的缩略图的宽和高都小于MICRO_KIND，则类型要使用MICRO_KIND作为kind的值，这样会节省内存。
     *
     * @param videoPath 视频的路径
     * @param kind      参照MediaStore.Images.Thumbnails类中的常量MINI_KIND和MICRO_KIND。
     *                  其中，MINI_KIND: 512 x 384，MICRO_KIND: 96 x 96
     * @return 指定大小的视频缩略图
     */
    public Bitmap getVideoThumbnail(String videoPath, int kind) {
        if (!new File(videoPath).exists()) {
            return null;
        }
        Bitmap bitmap = null;
        // 获取视频的缩略图
        bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);
        System.out.println("w" + bitmap.getWidth());
        System.out.println("h" + bitmap.getHeight());
        int width = 120;
        int height = 120;
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return (bitmap);
    }

    public Bitmap createWebVideoThumbnail(final String url) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        int kind = MediaStore.Video.Thumbnails.MINI_KIND;
        try {
            if (Build.VERSION.SDK_INT >= 14) {
                retriever.setDataSource(url, new HashMap<String, String>());
            } else {
                retriever.setDataSource(url);
            }
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException ex) {
            // Assume this is a corrupt video file
        } catch (RuntimeException ex) {
            // Assume this is a corrupt video file.
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException ex) {
                // Ignore failures while cleaning up.
            }
        }
        if (kind == Images.Thumbnails.MICRO_KIND && bitmap != null) {
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, 120, 120,
                    ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        }
        return (bitmap);
    }

    public Bitmap getImageLoad(String url) {
//        Bitmap bitmap = ImageLoader.getInstance().loadImageSync(
//                "file:///" + url);
//        Bitmap bitmap =      Glide.with(XbbApplication.mContext).load(url).a;
        Bitmap myBitmap = null;
        try {
//            url = "file:///" + url;
            myBitmap = Glide.with(XbbApplication.mContext)
                    .asBitmap()
                    .load(new File(url))
                    .submit()
                    .get();
        } catch (Exception e) {
            e.printStackTrace();
        }


        return myBitmap;
    }

    /**
     * 读取图片属性：旋转的角度
     *
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return degree;
    }

    /*
     * 旋转图片
     *
     * @param angle
     *
     * @param bitmap
     *
     * @return Bitmap
     */
    public Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        // 旋转图片 动作
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        System.out.println("angle2=" + angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }

    //
    // public void rotateImageToNormal(File imageFile) {
    // Bitmap bitmapFromSD = AbFileUtil.getBitmapFromSD(imageFile);
    // int readPictureDegree = ImageUtil.readPictureDegree(imageFile
    // .getAbsolutePath());
    // if (readPictureDegree != 0) {
    // Bitmap rotaingImageView = ImageUtil.rotaingImageView(
    // readPictureDegree, bitmapFromSD);
    // byte[] bitmap2Bytes = AbImageUtil.bitmap2Bytes(rotaingImageView,
    // CompressFormat.PNG, true);
    // String name = imageFile.getName();
    // String absolutePath2 = imageFile.getParentFile().getAbsolutePath();
    // LogUtil.i(debug, TAG,
    // "【PhotoActivity.onActivityResultCallback()】【name=" + name
    // + ",absolutePath2=" + absolutePath2 + "】");
    // FileUtil.byte2File(bitmap2Bytes, absolutePath2, name);
    // }
    // }

//    public Bitmap getImage(String url) {
//        Bitmap bitmap = ImageLoader.getInstance().loadImageSync(url);
//        return bitmap;
//    }

    public Bitmap getimage(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        // 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 800f;// 这里设置高度为800f
        float ww = 480f;// 这里设置宽度为480f
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;// 设置缩放比例
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
    }

    /**
     * 压缩图片
     *
     * @param image
     * @return
     */
    public Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    /**
     * Uri to the absolute file path (String)
     *
     * @param context
     * @param uri
     * @return the file path or null
     */
    public String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri)
            return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri,
                    new String[]{ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /**
     * bitmapToUri
     */
    public void bitmapToUri() {
        // Uri uri =
        // Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(),
        // bitmap, null,null));

    }

    /**
     * uriToBitmap
     */
    public void uriToBitmap() {
        // Bitmap bitmap =
        // MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);

    }

    /**
     * 获取APP所有图片缓存
     *
     * @return
     */
//    public String getAppAllImageCahe() {
//        DiskCache diskCache = ImageLoader.getInstance().getDiskCache();
//        File directory = diskCache.getDirectory();
//        FileUtil util = new FileUtil();
//        // + listFiles[i].getAbsolutePath() + "】");
//        String size = "";
//        try {
//            size = util.getFileOrFilesSize(directory.getAbsolutePath());
//        } catch (Exception e) {
//            LogUtil.i(debug, TAG, "【SettingAct.initData()】【e=" + e + "】");
//        }
//
//        return size;
//    }

    /**
     * 那么假如我们有一个图片的路径地址又该如何获得其Uri呢？
     */

    public void getUriFromPath(Intent intent) {

        //
        // String type = Utils.ensureNotNull(intent.getType());
        // Log.d(TAG, "uri is " + uri);
        // if (uri.getScheme().equals("file") && (type.contains("image/"))) {
        // String path = uri.getEncodedPath();
        // Log.d(TAG, "path1 is " + path);
        // if (path != null) {
        // path = Uri.decode(path);
        // Log.d(TAG, "path2 is " + path);
        // ContentResolver cr = this.getContentResolver();
        // StringBuffer buff = new StringBuffer();
        // buff.append("(")
        // .append(Images.ImageColumns.DATA)
        // .append("=")
        // .append("'" + path + "'")
        // .append(")");
        // Cursor cur = cr.query(
        // Images.Media.EXTERNAL_CONTENT_URI,
        // new String[] { Images.ImageColumns._ID },
        // buff.toString(), null, null);
        // int index = 0;
        // for (cur.moveToFirst(); !cur.isAfterLast(); cur
        // .moveToNext()) {
        // index = cur.getColumnIndex(Images.ImageColumns._ID);
        // // set _id value
        // index = cur.getInt(index);
        // }
        // if (index == 0) {
        // //do nothing
        // } else {
        // Uri uri_temp = Uri
        // .parse("mContent://media/external/images/media/"
        // + index);
        // if (uri_temp != null) {
        // uri = uri_temp;
        // }
        // }
        // }
        // }

    }
}
